package com.lzw.main;

import com.lzw.app.Instance;
import com.lzw.app.ServerApp;
import com.lzw.data.AppRepository;

import java.util.Map;
import java.util.Set;

/**
 * 日志打印线程
 * @author LZW
 */
public class ShowThread implements Runnable {
    private ServerApp serverApp;

    public ShowThread(ServerApp serverApp) {
        this.serverApp = serverApp;
    }

    public void run() {
        while (true) {
            showService(serverApp.getAppRepository(), "服务");
            showService(serverApp.getServerRepository(), "集群");
            try {
                Thread.sleep(60000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void showService(AppRepository appRepository, String type) {
        StringBuilder sb = new StringBuilder();
        sb.append(type).append(":");
        Map<String, Map<String, Instance>> data = appRepository.getData();
        Set<String> names = data.keySet();
        if (names.size() > 0) {
            for (String name : names) {
                sb.append("\n\r\t\t").append("name: ").append(name);
                Map<String, Instance> instanceMap = data.get(name);
                if (instanceMap != null && instanceMap.size() > 0) {
                    Set<String> ids = instanceMap.keySet();
                    for (String id : ids) {
                        Instance instance = instanceMap.get(id);
                        if (instance != null) {
                            sb.append("\n\r\t\t\t").append("ip+port: ").append("http://").append(instance.getHost()).append(":").append(instance.getPort())
                                    .append("  ---> id: ").append(id);
                        }
                    }
                }
            }
        }
        System.out.println(sb);
    }
}
